package com.wcpdoc.exam.api.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExamUserTokenUtils {
    private final Object lock = new Object();







    /**
     * 每场考试设置一个唯一标识，等考试完结后就移除
     */
    private static Map<Integer, Map<Integer, List<String>>> mapExamUserToken=new HashMap<>();

    /**
     * 单例
     */
    private static ExamUserTokenUtils examUserTokenUtils=new ExamUserTokenUtils();
    private ExamUserTokenUtils(){}
    public static ExamUserTokenUtils getInstance(){
        return examUserTokenUtils;
    }


    /**
     * 开始正式考试，设置一个token
     * @param examId
     * @param userId
     * @param token
     */
    public void setExamUserToken(Integer examId, Integer userId, String token){
        try {
            synchronized(lock){
                if (mapExamUserToken.containsKey(examId)) {
                    Map<Integer, List<String>> mapUserToken = mapExamUserToken.get(examId);
                    if (mapUserToken.containsKey(userId)) {
                        mapUserToken.get(userId).add(token);
                    } else {
                        mapUserToken.put(userId, new java.util.ArrayList<String>());
                        mapUserToken.get(userId).add(token);
                    }
                } else {
                    mapExamUserToken.put(examId, new HashMap<Integer, List<String>>());
                    mapExamUserToken.get(examId).put(userId, new java.util.ArrayList<String>());
                    mapExamUserToken.get(examId).get(userId).add(token);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断当前是否在正式考试期间多次登录
     * @param examId
     * @param userId
     * @return true，未超过2次，false 超过2次
     */
    public Boolean isVaild(Integer examId, Integer userId){
        if(mapExamUserToken.containsKey(examId)){
            Map<Integer, List<String>> mapUserToken=mapExamUserToken.get(examId);
            if(mapUserToken.containsKey(userId)){
                return mapUserToken.get(userId).size()<=2;
            }
        }
        return true;
    }

    /**
     *  移除token
     * @param examId
     * @param userId
     */
    public void remove(Integer examId, Integer userId){
        try {
            synchronized(lock){
                if(mapExamUserToken.containsKey(examId)){
                    Map<Integer, List<String>> mapUserToken=mapExamUserToken.get(examId);
                    if(mapUserToken.containsKey(userId)){
                        mapUserToken.remove(userId);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
